<template>
  <div class="avue-top">
    <div class="top-bar__left">
      <div class="avue-breadcrumb"
           :class="[{ 'avue-breadcrumb--active': isCollapse }]"
           v-if="showCollapse">
        <i class="icon-navicon"
           @click="setCollapse"></i>
      </div>
    </div>
    <div class="top-bar__title">
      <div class="top-bar__item top-bar__item--show"
           v-if="showMenu">
        <top-menu></top-menu>
      </div>
      <span class="top-bar__item"
            v-if="showSearch">
        <top-search></top-search>
      </span>
    </div>
    <div class="top-bar__right">
      
      <el-tooltip v-if="showColor"
                  effect="dark"
                  :content="$t('navbar.color')"
                  placement="bottom">
        <div class="top-bar__item">
          <top-color></top-color>
        </div>
      </el-tooltip>
      <el-tooltip v-if="showDebug"
                  effect="dark"
                  :content="logsFlag?$t('navbar.bug'):logsLen+$t('navbar.bugs')"
                  placement="bottom">
        <div class="top-bar__item">
          <top-logs></top-logs>
        </div>
      </el-tooltip>
      <el-tooltip v-if="showLock"
                  effect="dark"
                  :content="$t('navbar.lock')"
                  placement="bottom">
        <div class="top-bar__item">
          <top-lock></top-lock>
        </div>
      </el-tooltip>
      <el-tooltip v-if="showTheme"
                  effect="dark"
                  :content="$t('navbar.theme')"
                  placement="bottom">
        <div class="top-bar__item top-bar__item--show">
          <top-theme></top-theme>
        </div>
      </el-tooltip>

      <el-tooltip v-if="showAsync"
                  effect="dark"
                  content="同步设置"
                  placement="bottom">
        <div class="top-bar__item">
          <top-async></top-async>
        </div>
      </el-tooltip>
      <el-tooltip v-if="showMsg"
                  effect="dark"
                  content="消息"
                  placement="bottom">
        <div class="top-bar__item">
          <top-msg></top-msg>
        </div>
      </el-tooltip>

      <!-- <el-tooltip effect="dark"
                  :content="$t('navbar.language')"
                  placement="bottom">
        <div class="top-bar__item top-bar__item--show">
          <top-lang></top-lang>
        </div>
      </el-tooltip> -->
      <el-tooltip v-if="showFullScren"
                  effect="dark"
                  :content="isFullScren?$t('navbar.screenfullF'):$t('navbar.screenfull')"
                  placement="bottom">
        <div class="top-bar__item">
          <i :class="isFullScren?'icon-tuichuquanping':'icon-quanping'"
             @click="handleScreen"></i>
        </div>
      </el-tooltip>
      <img class="top-bar__img"
           :src="userInfo.avatar">
      <el-dropdown>
        <span class="el-dropdown-link">
          {{userInfo.realName}}
          <i class="el-icon-arrow-down el-icon--right"></i>
        </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item>
            <router-link to="/wel/index">{{$t('navbar.dashboard')}}</router-link>
          </el-dropdown-item>
          <el-dropdown-item>
            <router-link to="/info/index">{{$t('navbar.userinfo')}}</router-link>
          </el-dropdown-item>
          <el-dropdown-item @click.native="logout"
                            divided>{{$t('navbar.logOut')}}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
  </div>
</template>
<script>
import {querySysMsgNoticeList} from '@/api/system/sysMsgNoticeApi';
import {reqCommonMsg } from '@/util/reqCommonMsg';
import { mapGetters, mapState } from 'vuex';
import { fullscreenToggel, listenfullscreen } from '@/util/util';
import topLock from './top-lock';
import topMenu from './top-menu';
import topSearch from './top-search';
import topTheme from './top-theme';
import topLogs from './top-logs';
import topColor from './top-color';
import topLang from './top-lang';
import topAsync from './top-async';
import topMsg from './top-msg';
import { Base64 } from 'js-base64';
export default {
  components: {
    topLock,
    topMenu,
    topSearch,
    topTheme,
    topLogs,
    topColor,
    topLang,
    topAsync,
    topMsg
  },
  name: 'top',
  data() {
    return {
      //是否允许多处登录
      allowMutiLogin: false,

      noticeSocket: null,
      socket: null,
      timer: null,
      data: [],
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  filters: {},
  created() {
    this.$store.dispatch('setMsgObject',{msgBox: true,notReadCnt: 0});
    //检测用户状态信息
    setTimeout(() => {
      this.getSysParam().then((data) => {
        if(data == true){
          this.logInSocket();
        }
      })
    }, 2000);

    //消息通知连接
    this.getNoticeSocket();
    setTimeout(() => {
      if(this.msgObject.msgBox){
        this.onLoad();
      }
    }, 2000);
  },
  mounted() {
    listenfullscreen(this.setScreen);
  },
  computed: {
    ...mapState({
      showDebug: state => state.common.showDebug,
      showTheme: state => state.common.showTheme,
      showLock: state => state.common.showLock,
      showFullScren: state => state.common.showFullScren,
      showCollapse: state => state.common.showCollapse,
      showSearch: state => state.common.showSearch,
      showMenu: state => state.common.showMenu,
      showColor: state => state.common.showColor,
      showAsync: state => state.common.showAsync,
      showMsg: state => state.common.showMsg
    }),
    ...mapGetters([
      'userInfo',
      'isFullScren',
      'tagWel',
      'tagList',
      'isCollapse',
      'tag',
      'logsLen',
      'logsFlag',
      'msgObject',
      'socketConnection',
      'msgObject'
    ])
  },
  watch:{
    msgObject: {
      handler(newValue, oldValue) {
        if(newValue.msgBox){
          this.getNoticeSocket();
        }
      },
      deep: true
    }
  },
  methods: {
    /**
     * 获取工作日参数
     */
    async getSysParam() {
      let sysParamData = await this.$params.getSysParam('allowMutiLogin');
      this.$console.log('===>getSysParam='+sysParamData.allowMutiLogin);
      return sysParamData.allowMutiLogin;
    },

    handleScreen() {
      fullscreenToggel();
    },
    setCollapse() {
      this.$store.commit('SET_COLLAPSE');
    },
    setScreen() {
      this.$store.commit('SET_FULLSCREN');
    },
    logout() {
      this.$confirm(this.$t('logoutTip'), this.$t('tip'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(() => {
        this.doLogout();
      });
    },

    doLogout(){
      const loading = this.$loading({
        lock: true,
        text: '正在退出...',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 1)'
      });
      this.$store.dispatch('LogOut').then(() => {
        setTimeout(() => {
          window.location.href='/#/index?tenantId='+localStorage.getItem('tenantId')+'&v1';
          window.location.reload();
        }, 1000);
      });
    },
    /** 
     * 上线下线通知
     */
    logInSocket() {
      const that = this;
      if (typeof (WebSocket) == 'undefined') {
        this.$notify({
          title: '提示',
          message: '当前浏览器无法接收实时报警信息，请使用谷歌浏览器！',
          type: 'warning',
          duration: 0
        });
      } else {

        // 实例化socket，这里我把用户名传给了后台，使后台能判断要把消息发给哪个用户，其实也可以后台直接获取用户IP来判断并推送
        const socketUrl = 'ws://socket.dooleen.com:8012/webSocket/loginUser/'+this.userInfo.tenantId+'/PC/'+this.userInfo.userName+'/'+this.userInfo.realName+'/'+ Base64.encode(this.userInfo.avatar || 'abc')+'/'+localStorage.getItem('accessId');
        if(this.socket!=null){
          this.socket.close();
          this.socket = null;
        }
        this.socket = new WebSocket(socketUrl);
        // 监听socket打开
        this.socket.onopen = function() {
          that.$console.log('浏览器WebSocket已打开');
        };
        // 监听socket消息接收
        this.socket.onmessage = function(msg) {
          that.$console.log('msg==',msg);
          // 转换为json对象 
          let echoMsg = JSON.parse(msg.data);
          //alert(msg.data);
          if(echoMsg.type == 'login'){
            let noticeStr = '<div>用户：<span style="font-weight:bold;">'+echoMsg.userInfo.userName+'</span> 已于 <span style="font-weight:bold;">'+echoMsg.userInfo.loginTime+'</span> 在IP为 <span style="font-weight:bold;">'+echoMsg.userInfo.address+'</span> 的终端登录！</div>';
            that.$alert(noticeStr, '下线提醒', {
              dangerouslyUseHTMLString: true,
              confirmButtonText: '我知道了',
              callback: action => {
                that.doLogout();
              }
            });
          }
        };
        // 监听socket错误
        this.socket.onerror = function() {
          that.$console.error('==>>上线下线通知，服务器错误，无法接收实时信息');
        };
        // 监听socket关闭
        this.socket.onclose = function() {
          that.$console.log('WebSocket已关闭');
        }
      }
    },
    /**
     * 加载消息列表数据，获取未读条数
     */
    onLoad() {
      this.commonData = reqCommonMsg(this.reqParams)
      querySysMsgNoticeList(this.commonData).then(res => {
        this.noticeMsgList = res.data.body.listBody;
        let notReadCnt = 0;
        this.noticeMsgList.forEach(element => {
          if(element.notReadCnt > 0){
            notReadCnt += element.notReadCnt;
          }
        });
        //更新未读条数
        this.$store.dispatch('setMsgObject',{msgBox: true,notReadCnt: notReadCnt});
      }, error => {
      });
    },
    /**
     * 判断链接是否有效
     */
    getNoticeSocket(){
      this.handleSocketMsg();
    },
    /** 
     * 消息通知
     */
    handleSocketMsg() {
      console.log('开始连接001...',);
      //如果断开，则重新链接；
      if(!this.socketConnection || this.socketConnection.readyState != this.socketConnection.OPEN){
        this.$store.dispatch('setSocketConnection', this.userInfo);
      }
      let that = this;
      this.socketConnection.onmessage = function(msg) {
        that.$console.log('消息内容001 msg==',msg);
        let msgData = JSON.parse(msg.data);
        if(msgData.type && msgData.type == 'command'){
        //清理缓存并退出
          if(msgData.commandName == 'clearStorage'){
            let tenantId = localStorage.getItem('tenantId');
            that.$clearStore();
            that.$clearStore({type: 's'});
            window.location.href='/#/index?tenantId='+tenantId+'&v1';
            window.location.reload();
          }
        }
        //处理接收到的消息
        if(msgData.type && msgData.type == 'message'){
          that.$store.dispatch('setMsgObject',{msgBox: false,notReadCnt: (that.msgObject.notReadCnt + 1)});
          let content ={
            title: msgData.sendRealName,
            body: msgData.msgTitle,
            icon: msgData.senderHeadImgUrl
          }
          that.notify(content);
        }
      };
    },
    /**
     * 新消息浏览器通知
     */
    notify(content){
      var that = this;
      var notification = new Notification(content.title, {
        body: content.body,
        icon: content.icon || 'https://avatar.csdnimg.cn/B/D/8/1_qq_34273059.jpg',
        data: {
          url: content.url || '/notice/index'
        }
      });
      notification.onclick = function() {
        this.$console.log('==>>点击了消息');
        that.$router.push({ path: notification.data.url});
      };
      notification.onclose = function () {
        this.$console.log('==>>消息已关闭');
      }
      notification.onerror = function (err) {
        console.log('==>>通知出错了，请检查权限..');
        throw err;
      }
    }
  }
};
</script>
<style>
.logoutStyle{
  color:red;
}
</style>
